import { Fragment, defineComponent, reactive } from 'vue';
import "fengmap/build/fengmap.map.min.js";
import "fengmap/build/fengmap.analyser.min";
import "fengmap/build/fengmap.plugin.min";
import "fengmap/build/fengmap.effect.min";
import "fengmap/build/fengmap.plugin.ui.min";
import 'fengmap/build/toolBarStyle.css';
import { mapBox, resumeNavigation, device_modal, title, des, btn, dialogCenter, dialogTitle, dialogBtnGroup, dialogBtnDefault, dialogBtnPrimary, toolBarDiv, layuiBtn } from './Fmap.module.scss';
import { map, marker, navi, poi, url } from "@/store";
import websocket from '@/utils/websocket';
import { compassHeading } from '@/utils/compass';
import aoaController from "@/utils/aoaController"
import control from '@/utils/control';
import { closeToast, showLoadingToast } from 'vant';
import { Dialog as VantDialog } from 'vant';
import img1 from '@/assets/img/allow-compass.png';
import device from '@/assets/img/device.png';
import img2 from '@/assets/img/allow-beacon.png';
import { locationMarker } from '@/store/modules/marker';
import MyLoading from '@/components/loading/Loading'

import logoImg from '@/assets/img/logo.png';
import View from '../controls/view/View';
import FloorControl from '../controls/floor/FloorControl';
import Location from '../controls/location/Location';
import Zoom from '../controls/zoom/Zoom';
import { detailsObj } from '../details/Details';
import { walkNaviPoints } from '@/utils/record';

/*
---地图渲染文件
---重构：5
*/
export const fmapObj = reactive({
    top: '-1',
    isRecord: false,//是否开启重现定位导航
})
export default defineComponent({
    name: 'Fmap',
    data() {
        return {
            baiduLayer: null as any,
            // isLoading: false,
            count: 3,
            confirmTimer: null as any,
        };
    },
    mounted() {
        // 解析url参数
        url.analysisUrl();
        // 建立websocket链接
        map.websocketObj = new websocket(map.getWssUrl);
        // 初始化地图
        this.initFmap();
    },
    methods: {
        initFmap() {
            // this.isLoading = true;
            showLoadingToast({
                message: '正在初始化...',
                forbidClick: true,
                duration: 0,
            });
            map.setMapContainer(document.getElementById("mapContainer"));
            // @ts-ignore
            map.fmap = new fengmap.FMMap(map.mapOptions);
            map.fmap.on("loaded", (event: any) => {
                console.log('地图加载完成');
                closeToast();

                map.floorInfos = map.fmap.getFloorInfos();

                map.setStatus({
                    map: {
                        load: true,
                        state: map.fmap.getState(),
                        zoom: map.fmap.getZoom(),
                        zoomRange: map.fmap.getZoomRange(),
                    },
                });

                //监听设备朝向
                window.addEventListener("deviceorientation", (event) => {
                    //@ts-ignore
                    let angle = event.webkitCompassHeading;
                    if (typeof angle === "undefined") {
                        // 校准罗盘方向
                        angle = compassHeading(event.alpha, event.beta, event.gamma);
                    }

                    // 导航或者非导航状态下都要转动 locationMarker
                    if (!map.compassUpdate) {
                        if (!map.centerFlag && locationMarker != null && !map.angleFlag) {
                            map.centerFlag = true;
                            locationMarker.rotateTo({
                                heading: -angle,
                                animate: true,
                                duration: 0.1,
                                finish: () => {
                                    // 导航状态下设置中心点
                                    if (navi.status && navi.coord.x > 0) {
                                        map.fmap.setCenter({
                                            x: navi.coord.x,
                                            y: navi.coord.y,
                                            animate: true,
                                            duration: 0.1,
                                            finish: () => {
                                                map.centerFlag = false;
                                            }
                                        })
                                    } else {
                                        map.centerFlag = false;
                                    }
                                }
                            });
                        }
                    } else {
                        //非导航状态下&&compassUpdate=true地图跟随指北针旋转
                        if (!navi.status && !map.centerFlag) {
                            map.centerFlag = true;
                            map.fmap.setRotation({
                                rotation: angle,
                                animate: true,
                                duration: 0.1,
                                finish: () => {
                                    map.centerFlag = false;
                                }
                            })
                        }
                    }
                }, true);

                //拾取对象时的过滤函数
                map.fmap.pickFilterFunction = function (event: any) {
                    // @ts-ignore
                    // console.log('pickFilterFunction', fengmap.FMType.MODEL, event.type, event.data.type);
                    let notAllowList = [300000, 100100, 300001, 310202];
                    // @ts-ignore
                    return !(event.type === fengmap.FMType.MODEL && notAllowList.includes(event.data.type));
                };

                //初始化导航
                map.initAnalyserNavigator();

                //初始化控件
                control.addControls();
                //设置控件监听事件
                this.addControlOnEvent();

                //初始化起点终点poi信息
                if (url.fid) poi.requestPoiInfo(url.fid);
            });

            // map.fmap.on('info', function (event) {
            //     // @ts-ignore
            //     console.log('info', fengmap.FMInfoMode.MAP_ID_URL_ERROR, fengmap.FMInfoMode.NAME_KEY_ERROR, fengmap.FMInfoMode.THEME_ID_URL_ERROR, fengmap.FMInfoMode.DEFAULT_LEVEL_ERROR, event);

            //     // @ts-ignore
            //     if (fengmap.FMInfoMode.MAP_ID_URL_ERROR === event.InfoMode) {
            //         console.log("您配置的mapID或者mapURL不正确，请访问蜂鸟云控制台检查您的地图");
            //     }
            //     // @ts-ignore
            //     if (fengmap.FMInfoMode.NAME_KEY_ERROR === event.InfoMode) {
            //         console.log("appName或key不正确");
            //     }
            //     // @ts-ignore
            //     if (fengmap.FMInfoMode.THEME_ID_URL_ERROR === event.InfoMode) {
            //         console.log("您配置的themeID或者themeURL不正确，请访问蜂鸟云控制台检查您的地图");
            //     }
            //     // @ts-ignore
            //     if (fengmap.FMInfoMode.DEFAULT_LEVEL_ERROR === event.InfoMode) {
            //         console.log("楼层不存在");
            //     }
            // });

            map.fmap.on("externalFirstLoaded", (event) => {
                // console.log("外部模型首次加载完成事件", event)
                setTimeout(() => {
                    closeToast();
                    // this.isLoading = false;
                    map.deviceMotionFlag = true;
                }, 300)
            });

            map.fmap.on("hover", (event: any) => {
                // console.log("鼠标划过事件", event)
                // this.setMoveMapFlag();
            });
            map.fmap.on("click", (event: any) => {
                console.log("鼠标点击事件", event)
                console.log(map.initModel, event.level, poi.infoType);

                if (map.initModel) {
                    map.initModel.resetColor();
                }

                if (event.level !== null) {
                    let data = {
                        x: event.coords.x,
                        y: event.coords.y,
                        floorId: event.level,
                        targets: event.targets,
                    };
                    if (!poi.infoType) return;
                    marker.removeImageMarker();
                    //显示标记（终点）
                    let FID = this.getFID(data.targets);

                    if (FID == 0) {
                        map.choiceFlag = false;
                        map.detailsFlag = false;
                        map.menuFlag = true;
                    } else {
                        console.log('获取poi详细信息');
                        poi.requestPoiInfo(FID, data.targets);
                        map.curPageType = "details";
                        //展示poi详细信息弹框
                        map.detailsFlag = true;
                        map.menuFlag = false;
                        map.listFlag = false;
                        marker.removeImageMarker();

                        poi.info.fid = FID;
                        poi.info.floorId = data.floorId;
                        poi.info.coordinateX = +data.x;
                        poi.info.coordinateY = +data.y;

                        //起点
                        poi.start = poi.now;
                        //终点
                        poi.end = poi.info;

                        //显示标记（终点）
                        marker.setImageMarker(
                            {
                                x: poi.end.coordinateX,
                                y: poi.end.coordinateY,
                                floorId: poi.end.floorId,
                            },
                            true
                        );
                    }
                }
            });

            return

            //开启定位
            aoaController.startPosition(url.tagid);
            aoaController.onAreaChange((inAoA: boolean) => {
                // isInAoA = inAoA
            });
            aoaController.onAOAPostion((pos: any) => {
                // if (isInAoA) {
                // 体验版需要aoa定位
                // position.value.x = pos.x
                // position.value.y = pos.y
                // }
            })

        },
        setMoveMapFlag() {
            navi.moveLocationCenter(20000);
        },
        addControlOnEvent() {
            map.fmap.on("levelChanged", (event: any) => {
                map.activeFloor = event.level;
            });
            map.fmap.on("zoom", (event: any) => {
                // console.log("地图缩放事件", event)
                if (event.zoom <= 18.8) {
                    this.addBaiduMap(map);
                } else {
                    // this.deleteBaiduMap(map)
                }
            });
        },
        addBaiduMap(map: any) {
            if (!this.baiduLayer) {
                // @ts-ignore
                this.baiduLayer = new fengmap.FMTileLayer({
                    //百度矢量图替换BAIDU_VECTOR
                    // @ts-ignore
                    mode: fengmap.FMTileProvider.AMAP_VECTOR,
                    offset: 1.0,
                })
                this.baiduLayer.addTo(map);
            }
        },
        deleteBaiduMap(map: any) {
            if (this.baiduLayer) {
                this.baiduLayer.remove(map);
                this.baiduLayer = null;
            }
        },
        getFID(arr: any) {
            for (let i = 0; i < arr.length; i++) {
                console.log(arr[i].FID);
                //TODO:FID过滤规则!arr[i].FID.includes('17')
                if (arr[i].FID) {
                    return arr[i].FID;
                }
            }
            return 0;
        },
        getDeviceMotion() {
            map.deviceMotionFlag = false;
            this.setDeviceMotion();
            setTimeout(() => {
                if (navi.curPosition.floorId == 0) {
                    // 表示没有获取到定位
                    map.noLocationDialog = true;
                    this.confirmTimer = setInterval(() => {
                        if (this.count !== 0) {
                            this.count--;
                        } else {
                            this.count = 3;
                            clearInterval(this.confirmTimer);
                            this.noLocationConfirm();
                        }
                    }, 1000)
                }
                // }, 10000)
                //TODO:csm测试
            }, 100)
        },
        setDeviceMotion() {
            // 获取设备定位和运动方向
            // @ts-ignore if (window.DeviceOrientationEvent !== undefined && typeof window.DeviceOrientationEvent.requestPermission === 'function') {
            if (window.DeviceMotionEvent !== undefined && typeof window.DeviceMotionEvent.requestPermission === 'function') {
                // @ts-ignore
                window.DeviceMotionEvent.requestPermission().then((response) => {

                    if (response == 'granted') {
                        window.addEventListener('devicemotion', () => {
                            // 处理
                            map.deviceMotionFlag = false;
                        });
                        // window.addEventListener('deviceorientation', (event) => {
                        //     const { alpha, beta, gamma } = event;
                        // })
                    }
                }).catch(function (error) {
                    console.log("未授权运动与方向权限" + error);
                });

            } else {
                console.error("设备不支持DeviceMotion");
            }
        },
        setStartSimulatePoi() {
            console.log(`${navi.defaultName}位置`, navi.defaultPosition);
            poi.setNowPoi(navi.defaultPosition, navi.defaultName);
            if (navi.moveLocationFlag) {
                marker.setLocationMarker(navi.defaultPosition);
            }
            map.simulateDialog = false;
        },
        noLocationCancel() {
            map.noLocationDialog = false;
            if (this.confirmTimer) {
                this.count = 3;
                clearInterval(this.confirmTimer);
            }
            map.simulateDialog = true;
        },
        noLocationConfirm() {
            map.noLocationDialog = false
            // @ts-ignore
            wx.openLocation({
                latitude: 31.19214,
                longitude: 121.54151,
                name: '浦东图书馆',
                address: '浦东新区前程路88号近前程路与锦绣路交叉口',
                scale: 14,
                infoUrl: ''
            });
        },
        goNavigation() {
            //移动到当前位置
            navi.moveLocationFlag = true;
            locationMarker.moveTo({
                x: poi.now.coordinateX,
                y: poi.now.coordinateY,
                level: poi.now.floorId,
                animate: true,
                duration: .2,
                finish: () => {
                    navi.moveLocationFlag = false
                }
            })
        },
        backHome() {
            navi.resetNavigation();
            poi.infoType = "details";
            detailsObj.isLoading = false;
            map.routeInputFlag = false;
            map.pathFlag = false;
            map.menuFlag = true;
            map.routeFailedDialog = false
        },
        handleRecordBtn() {
            poi.start = {
                poiName: "开始位置",
                fid: "1",
                floorId: walkNaviPoints[0].level,
                coordinateX: walkNaviPoints[0].x,
                coordinateY: walkNaviPoints[0].y,
            };
            marker.setStart();
            poi.end = {
                poiName: "结束位置",
                fid: "2",
                floorId: walkNaviPoints[walkNaviPoints.length - 1].level,
                coordinateX: walkNaviPoints[walkNaviPoints.length - 1].x,
                coordinateY: walkNaviPoints[walkNaviPoints.length - 1].y,
            };

            if (navi.verifyRoutePois()) {
                showLoadingToast({
                    message: '路线规划中',
                    forbidClick: true,
                    duration: 0,
                });
                //规划路线并显示
                navi.startRoute();
                closeToast();
            }
        }
    },
    render() {
        const { deviceMotionFlag, simulateDialog, noLocationDialog, routeFailedDialog } = map;
        return <Fragment>
            <div class={mapBox}>
                <div id="mapContainer" style={{ width: '101vw', height: '101vh', position: 'absolute', top: `${fmapObj.top}px` }}></div>
                {/* 楼层控件 */}
                <FloorControl />
                {/* 视图切换 */}
                <View />
                {/* 定位控件 */}
                <Location />
                {/* 缩放控件 */}
                <Zoom />
                {/* 语音 */}
                <audio id="mp3Btn" style="height: 0" src={map.voiceSrc}></audio>
                {!fmapObj.isRecord ?
                    <div>
                        {/* 定位权限申请弹框 */}
                        <VantDialog show={deviceMotionFlag}
                            width={"70%"}
                            showConfirmButton={false}
                            showCancelButton={false}
                            closeOnClickOverlay={false}>
                            <div class={device_modal}>
                                <div class={title}>定位访问</div>
                                <img src={device} />
                                <div class={des}>为了您的定位更准确 需要开启您手机的“动</div>
                                <div class={btn} onClick={this.getDeviceMotion}>允许开启</div>
                            </div>
                        </VantDialog>
                        {/* 区域提示 */}
                        <VantDialog show={noLocationDialog}
                            width={"70%"}
                            showConfirmButton={false}
                            showCancelButton={false}
                            closeOnClickOverlay={false}>
                            <div class={dialogCenter}>
                                <div class={dialogTitle}>当前你不在馆内</div>
                                <div>是否需要切换室外导航地图</div>
                                <div class={dialogBtnGroup}>
                                    <div onClick={this.noLocationCancel} class={dialogBtnDefault}>取消</div>
                                    <div onClick={this.noLocationConfirm} class={dialogBtnPrimary}>确定({this.count}s)</div>
                                </div>
                            </div>
                        </VantDialog>
                        <VantDialog show={simulateDialog}
                            width={"70%"}
                            showConfirmButton={false}
                            showCancelButton={false}
                            closeOnClickOverlay={false}>
                            <div class={dialogCenter}>
                                <div class={dialogTitle}>当前你不在馆内</div>
                                <div >将以 {navi.defaultName} 作为起点</div>
                                <div onClick={this.setStartSimulatePoi} class={dialogBtnPrimary}>知道了</div>
                            </div>
                        </VantDialog>
                        <VantDialog show={routeFailedDialog}
                            width={"70%"}
                            showConfirmButton={false}
                            showCancelButton={false}
                            closeOnClickOverlay={false}>
                            <div class={dialogCenter}>
                                <div class={dialogTitle}>
                                    <div>路径规划失败</div>
                                    <div style={{ marginTop: '5px' }}>返回首页</div>
                                </div>
                                <div onClick={this.backHome} class={dialogBtnPrimary}>知道了</div>
                            </div>
                        </VantDialog>
                    </div> :
                    <div class={`${toolBarDiv} flex-center`}>
                        <button id="start" type="button" class={layuiBtn} onClick={this.handleRecordBtn}>开始重现导航</button>
                    </div>
                }
                {navi.status && !navi.moveLocationFlag && <div onClick={this.goNavigation} class={`${dialogCenter} ${resumeNavigation}`}>
                    <div class={dialogBtnDefault}>您已偏航，重新规划导航</div>
                </div>}
                {/* {this.isLoading && <MyLoading msg='正在加载地图中请稍后' img={logoImg} />} */}
            </div>
        </Fragment>;
    },
});